package net.dotool;

import java.util.ArrayList;
import java.util.List;
/**
 * 分割字符串，针对包含双引号的
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年1月15日 上午10:02:00
 *
 */
public class CSVTools {
	private static final char quotechar = '"';
	private static final char separator = ',';

	static final String NEWLINE = "\n";

	public static String[] parseLine(String nextLine, char separator) {
		if (nextLine == null) {
			return null;
		}

		List<String> tokensOnThisLine;
		try {
			tokensOnThisLine = new ArrayList<String>();
			StringBuilder sb = new StringBuilder();
			boolean inQuotes = false;
			do {
				for (int i = 0; i < nextLine.length(); i++) {
					final char c = nextLine.charAt(i);
					if (c == quotechar) {
						if (inQuotes && nextLine.length() > (i + 1) && nextLine.charAt(i + 1) == quotechar) {
							sb.append(nextLine.charAt(i + 1));
							i++;
						} else {
							inQuotes = !inQuotes;
							if (i > 2 && nextLine.charAt(i - 1) != separator && nextLine.length() > (i + 1) && nextLine.charAt(i + 1) != separator) {
								sb.append(c);
							}
						}
					} else if (c == separator && !inQuotes) {
						tokensOnThisLine.add(sb.toString());
						sb = new StringBuilder(); // start work on next token
					} else {
						sb.append(c);
					}
				}
			} while (inQuotes);
			tokensOnThisLine.add(sb.toString());
			return (String[]) tokensOnThisLine.toArray(new String[0]);
		} catch (Exception e) {
		}
		return nextLine.split(",");
	}
	
	public static String[] parseLine(String nextLine) {
		return parseLine(nextLine, separator);
	}


}